package middleware

import (
	"encoding/json"
	"gini2p/logger"
	. "gini2p/models"

	"github.com/gin-gonic/gin"

	"github.com/gin-contrib/sessions"
	"fmt"
	"net/http"
	"time"
	"gini2p/utility"
	"gini2p/config"
)

//执行前记录日志
func beforeMiddleHandle(c *gin.Context) {
	defer utility.PacnicStack()
	logger.Info("app", fmt.Sprint("************** Client : ", c.Request.RemoteAddr, " [", c.Request.Method, "] ", c.Request.URL.Path, "  from : [", c.Request.PostForm, "], *****************"))
	c.Next()
}

func BeforeRequestHandle() gin.HandlerFunc {
	return func(c *gin.Context) {
		session := sessions.Default(c)
		token_data := session.Get("token")
		var sessionData config.SessionData
		err := json.Unmarshal(token_data.([]byte), &sessionData)
		if err != nil {
			logger.Error("app", "解json字符串出错:", err)
		}
		token := c.Query("access_token")
		if len(token) == 0 {
			logger.Warn("manager", fmt.Sprint("token为空,强制退出"))
			c.JSON(http.StatusUnauthorized, gin.H{
				"status":  401,
				"message": "token为空",
			})
			c.Abort()
			return
		}
		manage, err := GetManageByToken(token)
		if err != nil {
			logger.Warn("manager", fmt.Sprint("用户不存在，强制退出"))
			c.JSON(http.StatusUnauthorized, gin.H{
				"status": 401,
			})
			c.Abort()
			return
		}
		if token != manage.AccessToken || token != sessionData.AccessToken {
			logger.Warn("manager", fmt.Sprint("token令牌不正确，强制退出"))
			c.JSON(http.StatusUnauthorized, gin.H{
				"status": 401,
			})
			c.Abort()
			return
		}
		if !sessionData.LastTime.Add(time.Minute * 30).After(time.Now()) {
			logger.Warn("manager", fmt.Sprint("操作超时,请重新登录"))
			c.JSON(http.StatusUnauthorized, gin.H{
				"status":  401,
				"message": "操作超时,请重新登录",
			})
			c.Abort()
			return
		}
		c.Next()
	}
}

func Init(r *gin.Engine) {
	r.Use(beforeMiddleHandle)
}
